/**************************************************************************
 * @name: B.c
 * @brief: 这个是共享内存的B进程，作为消费者
 * @date: 2025/02/12
 * @author: boluzs@163.com
 * @note: None
 * @version: 1.0.0
 * @Copyright (c) 2025 by boluzs@163.com, All Rights Reserved.
 **************************************************************************/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <stdlib.h>

#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main(int argc, char const *argv[])
{
    // 1.
    int shm_id = shmget(ftok("./A.c", 1), SHM_SIZE, IPC_CREAT | IPC_EXCL | 0666);
    if (shm_id == -1)
    {
        if (errno == EEXIST)
        {
            shm_id = shmget(ftok("./A.c", 1), SHM_SIZE, 0);
            if (shm_id == -1)
            {
                fprintf(stderr, "create shm error,errno = [%s]\n", strerror(errno));
                exit(-1);
            }
        }
        else
        {
            fprintf(stderr, "create shm error,errno = [%s]\n", strerror(errno));
            exit(-1);
        }
    }
    printf("shm_id=%d\n", shm_id);
    // 2.
    char *Date_Str = (char *)calloc(1, 32);
    time_t timer = time(NULL);
    struct tm *Date = localtime(&timer);
    sprintf(Date_Str, "日期: %.2d/%.2d/%.2d %.2d:%.2d:%.2d\n",
            Date->tm_year + 1900,
            Date->tm_mon + 1,
            Date->tm_mday,
            Date->tm_hour,
            Date->tm_min,
            Date->tm_sec);
    // 3.
    char *addr = (char *)shmat(shm_id, NULL, 0);
    if (addr == (void *)-1)
    {
        fprintf(stderr, "shmat error,%s\n", strerror(errno));
        exit(-2);
    }
    // 4.
    printf("str=%s\n", addr);
    return 0;
}
